package dper.study.codes.concurrent.worker;

import com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl;
import dper.study.codes.concurrent.model.ParellelResult;
import dper.study.codes.concurrent.model.ParellelType;
import org.apache.log4j.Logger;

import java.util.Random;
import java.util.Timer;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;

/**
 * Created by leichen on 2017/3/17.
 */
public class TimeSleepWorker implements Callable<ParellelResult>{
    private Logger logger = Logger.getLogger(TimeSleepWorker.class) ;
    private CountDownLatch countDownLatch = null ;
    private CyclicBarrier cyclicBarrier =null ;

    public TimeSleepWorker(){
    }

    public TimeSleepWorker(CountDownLatch countDownLatch){
        this.countDownLatch = countDownLatch ;
    }

    public TimeSleepWorker(CyclicBarrier cyclicBarrier){
        this.cyclicBarrier = cyclicBarrier ;
    }

    public ParellelResult call() throws Exception {
        try {
            Random rand = new Random();
            int millis = Math.abs(rand.nextInt()) % 10000 + 2000;
            logger.info("thread: " + Thread.currentThread() + " is working about " + millis + " millis");
            Thread.sleep(millis);
            ParellelResult ret = new ParellelResult();
            ret.setSuccess(true);
            ret.setResult(millis);
            ret.setParellelType(ParellelType.PT_TIME_SLEEP);
            return ret ;
        }finally {
            if(countDownLatch != null){
                countDownLatch.countDown();
            }
            if(cyclicBarrier != null){
                cyclicBarrier.await() ;
            }
        }
    }
}
